<template>
  <div class="app-container">
    <el-form  :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="日期" prop="ftdate">
        <el-date-picker clearable
          v-model="queryParams.ftdate"
          type="date"
          value-format="yyyy-MM-dd"
          @input="handleDateChange"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-button  v-show="total==0 && scsj" icon="el-icon-refresh" size="mini" @click="generateData">生成数据</el-button>
      <el-form-item  :gutter="10" class="mb3"   v-show="jyjcsh.flag>0 && JyjcShDatas.createBy"> 
    
         {{JyjcShDatas.createBy}}在{{JyjcShDatas.createTime}}{{JyjcShDatas.shName}}  
        </el-form-item>
     
        <div>
    <el-collapse v-model="activeNames">
      <el-collapse-item title="审核记录" name="1">
        <div v-for="item in JyjcShDataslist" :key="item.index" v-show="JyjcShDataslist != null">
          <el-form-item class="mb3">
            <span class="ml-10">{{ item.createBy }}</span>
            <span class="ml-10">{{ item.createTime }}</span>
            <span class="ml-10">{{ item.shName }}</span>
          </el-form-item>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
       <el-form-item label="年度" prop="year" v-show="false">
                <el-input v-model="queryParams.year" placeholder="请选择年度" clearable style="width: 240px" />
        </el-form-item>
              <el-form-item label="部门" prop="deptcode" v-show="false">
                <el-input v-model="queryParams.deptcode" placeholder="请选择部门" clearable style="width: 240px" />
              </el-form-item>
      <el-form-item  v-show="false">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item> 
    </el-form>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1010'"> 
  办公室(党群工作部)分摊表
 </el-row>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1011'"> 
  质量管理部分摊表
 </el-row>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1012'"> 
  财务内审部会计科分摊表
 </el-row>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1013'"> 
  科计规划研究所分摊表
 </el-row>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1014'"> 
  人力资源部分摊表
 </el-row>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1015'"> 
  设备管理部分摊表
 </el-row>
 <el-row :gutter="10" class="mb8"  style="text-align: center;font-size: 40px;"  v-show="queryParams.deptcode=='1016'"> 
  市场拓展部(业务协作部)分摊表
 </el-row>
 <el-row type="flex" justify="end">
    <el-col :span="3" style="font-size: 50px; color: red;">
      内部资料
    </el-col>
  </el-row>
    <el-row :gutter="10" class="mb8">
      
      <el-col :span="1.5">
        <el-button
        v-show="jyjcsh.flag==0 &&total>0"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >分摊</el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
        v-show="jyjcsh.flag==0&&total>0"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="sh" 
        >送审</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="expensesList" @selection-change="handleSelectionChange"  @expand-change="handleExpand" max-height="900">
     
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column type="expand"   >
       <template slot-scope="props"  >
        <div v-if="props.row.jyjcSharingExpensesDataList && props.row.jyjcSharingExpensesDataList">
            <div v-for="(child, index) in props.row.jyjcSharingExpensesDataList" :key="index" class="child-row">
              <el-row :gutter="20">
                <el-col :span="6">{{ child.ftDept }} ：{{ child.moneys }}</el-col>
              </el-row>
            </div>
          </div>
          <div v-else class="no-data">暂无子数据</div>
      </template>
    </el-table-column>
     <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="经济科目" align="center" prop="economicKm" />
      <el-table-column label="经济科目金额" align="center" prop="shflag" />
      <el-table-column label="包含的费用" align="center" prop="expenseType" />

      <el-table-column label="总金额" align="center" prop="zmoney" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
          v-if="scope.row.expenseType && jyjcsh.flag==0 "  
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >分摊</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用分摊对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body max-height="850">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="经济科目"   prop="economicKm">
          <el-input v-model="form.economicKm" readonly placeholder="请输入经济科目"  :style="{ 'font-weight': 'bold' }" />
        </el-form-item>
        <el-form-item label="经济科目金额" prop="shflag">
          <el-input v-model="form.shflag" placeholder="请输入经济科目金额" readonly type="number"  :style="{ 'font-weight': 'bold' }" />
        </el-form-item>
        <el-form-item label="包含费用"   prop="expenseType">
          <el-input v-model="form.expenseType" readonly placeholder="请输入包含的费用"  :style="{ 'font-weight': 'bold' }" />
        </el-form-item>
       
        <el-form-item label="总金额" prop="zmoney">
          <el-input v-model="form.zmoney" placeholder="请输入总金额"  type="number"/>
        </el-form-item>
        <el-divider content-position="center">分摊费用子信息</el-divider>
        <el-table  :default-sort="{prop:'orderNum', order:'ascending'}" :data="jyjcSharingExpensesDataList" :row-class-name="rowJyjcSharingExpensesDataIndex" @selection-change="handleJyjcSharingExpensesDataSelectionChange" ref="jyjcSharingExpensesData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="orderNum" width="50"/>
          <el-table-column label="分摊部门" prop="ftDept"  width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ftDept" readonly  placeholder="请输入分摊部门" />
            </template>
          </el-table-column>
          <el-table-column label="分摊金额" prop="moneys" width="250">
            <template slot-scope="scope">
              <el-input v-model="scope.row.moneys" 
              type="number" 
              placeholder="请输入分摊金额" 
              @focus="handleFocus(scope.row)"
              @blur="handleBlur(scope.row)"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExpenses, getExpenses, delExpenses, addExpenses, updateExpenses,generateData,UpdateFlag } from "@/api/system/expenses"
import { getjyjcSh } from "@/api/system/jyjcSh"
import { getJyjcShDatasLast ,getJyjcShDatasList } from "@/api/system/jyjcShDatas"
export default {
  name: "Expenses",
  // dicts: ['year', 'dept'],
  data() {
    return {
      activeNames: ['0'], // 默认展开
      JyjcShDataslist: null,
      JyjcShDatasQuery: {
        shId: ""
       
      },
      // 遮罩层
      loading: true,
      scsj:true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedJyjcSharingExpensesData: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用分摊表格数据
      expensesList: [],
      // 分摊费用子表格数据
      jyjcSharingExpensesDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        year: "",
        yf:"",
        deptcode: "",
        flag: "",
        ftdate:"",
        auditStatus: ''
      },
      updateflag:{
        ftdate:"",
        deptcode: "",
        flag:"",
        // 动作名称
        expenseType:""
      },
      jyjcsh: {
        yearyf: "",
        shtime:"",
        type: 'fyft',
        flag: "",
        createBy:"",
        createTime:""
      },
      JyjcShDatas: {
        createBy: "",
        createTime: "",
        shName: ""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        zmoney: [
          
            { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    const query = this.$route.query;
    this.queryParams.deptcode=query.deptcode;
    this.queryParams.ftdate = new Date().toISOString().split('T')[0];
    this.jyjcsh.shtime=new Date().toISOString().split('T')[0];
    this.jyjcsh.deptcode=query.deptcode;
    this.handleDateChange();
  },
  methods: {
      /** 查询费用分摊列表 */
    getList() {
      this.loading = true
      listExpenses(this.queryParams).then(response => {
        this.expensesList = response.rows
        this.total = response.total
        this.loading = false
        this.queryParams.auditStatus=response.rows[0].flag
        if(this.total>0){
          this.getjyjcSh()
        }
        children: []
      })
    },
    getjyjcSh() {
      
      getjyjcSh(this.jyjcsh).then(response => {
        this.jyjcsh.flag=response.data.flag
        this.jyjcsh.createBy=response.data.createBy
        this.jyjcsh.createTime=response.data.createTime
     
        this.getJyjcShDatasLast(response.data.id)
      })
    },
    getJyjcShDatasLast(id){
    
    getJyjcShDatasLast(id).then(response => {

      this.JyjcShDatas.shName=response.data.shName
      this.JyjcShDatas.createBy=response.data.createBy
      this.JyjcShDatas.createTime=response.data.createTime
    })
    this.getJyjcShDatasList(id);
  }, 
  getJyjcShDatasList(id){

    this.JyjcShDatasQuery.shId=id
    getJyjcShDatasList(this.JyjcShDatasQuery).then(response => {
   console.info(response.rows);
      this.JyjcShDataslist=response.rows
      
    })
  },
    generateData(){
      this.scsj = false
      generateData(this.queryParams).then(response => {
          this.$modal.msgSuccess("生成分摊数据成功")
          this.handleQuery()
            })
        
    },
    sh() {
        this.queryParams.auditStatus='1';
        this.updateflag.flag='1';
        this.updateflag.deptcode=this.queryParams.deptcode;
        this.updateflag.ftdate=this.queryParams.ftdate;
        this.updateflag.expenseType='送审';
      
        UpdateFlag(this.updateflag).then(
          this.$modal.msgSuccess("送审成功")

        );
        this.jyjcsh.flag="1";
        this.getjyjcSh();
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        year: null,
        deptcode: null,
        economicKm: null,
        expenseType: null,
        zmoney: null
      }
      this.jyjcSharingExpensesDataList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 日期改变时出发方法 */
    handleDateChange(){
      this.queryParams.pageNum = 1
      const [y, m, d] = this.queryParams.ftdate.split('-');
       this.queryParams.year=y
       this.queryParams.yf=m
       this.jyjcsh.deptcode=this.queryParams.deptcode;
       this.jyjcsh.shtime=this.queryParams.ftdate;
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加费用分摊"
    },
    handleExpand(row,expandedRows) {
if (expandedRows.includes(row)) {
    if (!row.loaded) {
      this.$set(row, 'loading', true);
      const id = row.id || this.ids
      getExpenses(id).then(response => {
        this.$set(row, 'jyjcSharingExpensesDataList', response.data.jyjcSharingExpensesDataList);
      })
    }
  }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getExpenses(id).then(response => {
        this.form = response.data
        this.jyjcSharingExpensesDataList = response.data.jyjcSharingExpensesDataList
        this.open = true
        this.title = "修改费用分摊"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        
        if (valid) {
            

          this.form.jyjcSharingExpensesDataList = this.jyjcSharingExpensesDataList
          let total = 0;
      for (const item of this.jyjcSharingExpensesDataList) {
          const amount = parseFloat(item.moneys);
           total += isNaN(amount) ? 0 : amount;
         }
        
        if (Math.abs(total - parseFloat(this.form.zmoney)) > 0.01) {
          this.$message.error('分摊金额总和必须等于总金额')
          return
        }
        if (this.form.id != null) {
            updateExpenses(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addExpenses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除费用分摊编号为"' + ids + '"的数据项？').then(function() {
        return delExpenses(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
 

	/** 分摊费用子序号 */
    rowJyjcSharingExpensesDataIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 分摊费用子添加按钮操作 */
    handleAddJyjcSharingExpensesData() {
      let obj = {}
      obj.ftDept = ""
      obj.moneys = ""
      this.jyjcSharingExpensesDataList.push(obj)
    },
    /** 分摊费用子删除按钮操作 */
    handleDeleteJyjcSharingExpensesData() {
      if (this.checkedJyjcSharingExpensesData.length == 0) {
        this.$modal.msgError("请先选择要删除的分摊费用子数据")
      } else {
        const jyjcSharingExpensesDataList = this.jyjcSharingExpensesDataList
        const checkedJyjcSharingExpensesData = this.checkedJyjcSharingExpensesData
        this.jyjcSharingExpensesDataList = jyjcSharingExpensesDataList.filter(function(item) {
          return checkedJyjcSharingExpensesData.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleJyjcSharingExpensesDataSelectionChange(selection) {
      this.checkedJyjcSharingExpensesData = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/expenses/export', {
        ...this.queryParams
      }, `expenses_${new Date().getTime()}.xlsx`)
    },
    handleFocus(row) {
    // 当获取焦点时，如果是0.00则清空以便输入
    if (row.moneys === '0.00' || row.moneys === 0 || row.moneys === '0.0') {
      row.moneys = '';
    }
  },
  handleBlur(row) {
    // 当失去焦点时，如果为空则恢复为0.00
    if (!row.moneys) {
      row.moneys = '0.00';
    } else {
      // 确保格式为两位小数
      const num = parseFloat(row.moneys);
      if (!isNaN(num)) {
        row.moneys = num.toFixed(2);
      }
    }
  }
  }
}
</script>
